<template>
  <div class="app-container">
    <el-card>
      <div class="page-header">
        <el-page-header @back="goBack" :content="paperTitle + ' - 学生答卷'" />
      </div>
      
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" class="mt20">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input
            v-model="queryParams.studentName"
            placeholder="请输入学生姓名"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input
            v-model="queryParams.studentId"
            placeholder="请输入学号"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="批阅状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择批阅状态" clearable style="width: 240px">
            <el-option label="已批阅" value="1" />
            <el-option label="未批阅" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="studentList" stripe>
        <el-table-column label="学号" align="center" prop="studentId" :show-overflow-tooltip="true"/>
        <el-table-column label="姓名" align="center" prop="studentName" />
        <el-table-column label="班级" align="center" prop="className" />
        <el-table-column label="提交时间" align="center" width="160">
          <template #default="scope">
            <div class="time-display">
              <i class="el-icon-time"></i>
              <span>{{ scope.row.submitTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用时" align="center" width="140">
          <template #default="scope">
            <div class="duration-display">
              <i class="el-icon-timer"></i>
              <span class="exam-time">{{ formatExamTime(scope.row.examTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="得分" align="center">
          <template #default="scope">
            <div class="score-display">
              <div :class="getScoreClass(scope.row.score, scope.row.totalScore)">
                {{ parseFloat(scope.row.score || 0).toFixed(1) }}
              </div>
              <span class="score-separator">/</span>
              <div class="total-score">
                {{ parseFloat(scope.row.totalScore || 0).toFixed(1) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="批阅状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" :effect="scope.row.status === 0 ? 'light' : 'light'">
              {{ scope.row.status === 1 ? '已批阅' : '未批阅' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="Edit"
              @click="handleMarkPaper(scope.row)"
            >{{ scope.row.status === 1 ? '查看批阅' : '批阅' }}</el-button>
            <el-button
              type="danger"
              link
              icon="Delete"
              @click="handleDeleteAnswer(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getStudentList"
      />
    </el-card>
  </div>
</template>

<script>
import { getAnswersByPaperId, deleteStudentAnswer } from '@/api/manage/mark'

export default {
  name: 'MarkAnswers',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷ID
      paperId: '',
      // 试卷标题
      paperTitle: '试卷批阅',
      // 学生列表
      studentList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: undefined,
        studentId: undefined,
        status: undefined
      }
    }
  },
  created() {
    this.paperId = this.$route.params.paperId
    this.getStudentList()
  },
  activated() {
    // 当页面被激活时（例如从详情页返回），重新获取数据
    if (this.paperId) {
      this.getStudentList()
    }
  },
  methods: {
    /** 查询学生答卷列表 */
    getStudentList() {
      this.loading = true
      getAnswersByPaperId(this.paperId, this.queryParams).then(response => {
        this.studentList = response.rows || []
        this.total = response.total
        
        // 如果有数据，获取试卷名称
        if (this.studentList.length > 0 && this.studentList[0].paperName) {
          this.paperTitle = this.studentList[0].paperName
        }
        
        this.loading = false
      }).catch(error => {
        console.error('获取学生答卷列表失败:', error)
        this.$message.error('获取学生答卷列表失败')
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getStudentList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 批阅试卷按钮操作 */
    handleMarkPaper(row) {
      // 构造答卷ID: studentId_paperId
      const answerId = row.studentId + '_' + this.paperId
      
      this.$router.push({
        name: 'MarkDetail',
        params: { answerId: answerId }
      })
    },
    /** 删除答题记录按钮操作 */
    handleDeleteAnswer(row) {
      this.$modal.confirm('确定要删除该学生的答题记录吗？删除后该学生可以重新参加考试。').then(() => {
        this.loading = true
        deleteStudentAnswer(this.paperId, row.studentId).then(response => {
          this.$modal.msgSuccess("删除成功")
          this.getStudentList()
        }).catch(error => {
          console.error('删除答题记录失败:', error)
          this.$modal.msgError('删除答题记录失败')
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {})
    },
    /** 返回按钮操作 */
    goBack() {
      this.$router.push({ path: '/paper/mark' })
    },
    /** 获取分数样式类 */
    getScoreClass(score, totalScore) {
      if (!score || !totalScore) return 'score-fail'
      
      const percentage = (parseFloat(score) / parseFloat(totalScore)) * 100
      
      if (percentage >= 90) {
        return 'score-excellent'
      } else if (percentage >= 80) {
        return 'score-good'
      } else if (percentage >= 60) {
        return 'score-pass'
      } else {
        return 'score-fail'
      }
    },
    /** 格式化用时显示 */
    formatExamTime(examTime) {
      if (!examTime) return '-'
      
      // 如果已经是格式化好的字符串，如"3小时29分7秒"，直接返回
      if (typeof examTime === 'string' && (examTime.includes('小时') || examTime.includes('分') || examTime.includes('秒'))) {
        // 对于仅有分秒格式的，如果分钟过大(>=60)，转换为小时分钟格式
        if (!examTime.includes('小时') && examTime.includes('分')) {
          const minutesMatch = examTime.match(/(\d+)分/);
          if (minutesMatch && parseInt(minutesMatch[1]) >= 60) {
            const minutes = parseInt(minutesMatch[1]);
            const hours = Math.floor(minutes / 60);
            const remainingMinutes = minutes % 60;
            let result = hours + '小时';
            if (remainingMinutes > 0) {
              result += remainingMinutes + '分';
            }
            // 处理秒数
            const secondsMatch = examTime.match(/(\d+)秒/);
            if (secondsMatch) {
              result += secondsMatch[1] + '秒';
            }
            return result;
          }
        }
        return examTime;
      }
      
      // 如果是 HH:MM:SS 格式
      if (typeof examTime === 'string' && examTime.includes(':')) {
        const parts = examTime.split(':')
        if (parts.length === 3) {
          const hours = parseInt(parts[0])
          const minutes = parseInt(parts[1])
          const seconds = parseInt(parts[2])
          
          let result = ''
          if (hours > 0) {
            result += hours + '小时'
          }
          if (minutes > 0 || hours > 0) {
            result += minutes + '分'
          }
          result += seconds + '秒'
          
          return result
        }
      }
      
      return examTime
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}

.time-display, .duration-display {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #4cb4fe;
}

.time-display i, .duration-display i {
  margin-right: 5px;
  color: #909399;
}

.score-display {
  display: flex;
  justify-content: center;
  align-items: center;
}

.score-separator {
  margin: 0 5px;
  color: #909399;
}

.total-score {
  color: #606266;
  font-weight: bold;
}

.exam-time {
  font-weight: bold;
  color: #ff9900; /* 橙色 */
}

/* 成绩样式 - 只设置文字颜色不设置背景色 */
.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-pass {
  color: #303133;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}
</style>

